package com.campus.fitter;

import com.campus.response.ResponseResult;
import com.campus.response.ResultCode;
import com.campus.util.JWTUtil;
import com.fasterxml.jackson.databind.util.JSONPObject;
import io.jsonwebtoken.Claims;
import io.swagger.v3.core.util.Json;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class UserFitter extends OncePerRequestFilter {
    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        String token = request.getHeader("token");
        ResponseResult<Object> responseResult=new ResponseResult<>(ResultCode.NO_LOGIN,null);
        String responseString= Json.pretty(responseResult);
        if (Objects.isNull(token)){
            filterChain.doFilter(request,response);
            return;
        }
        Integer userId;
        String role;
        try {
            Claims claims = jwtUtil.parserJwt(token);
            userId = (Integer) claims.get("userId");
            role=(String) claims.get("role");
        } catch (Exception e) {
            log.error("出现异常{}",ResultCode.NO_LOGIN.getMessage());
            response.getWriter().write(responseString);
            return;
        }
        //使用Redis存储，防止更改密码失效
        String redisToken= (String) redisTemplate.opsForValue().get("token:"+userId);
        if (Objects.isNull(redisToken)){
            response.getWriter().write(responseString);
            return;
        }
        if (!redisToken.equals(token)){
            response.getWriter().write(responseString);
            return;
        }
        if (role == null || role.isEmpty()) {
            return;
        }

        List<SimpleGrantedAuthority> simpleGrantedAuthorities = List.of(new SimpleGrantedAuthority("ROLE_" + role));
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                =new UsernamePasswordAuthenticationToken(userId,null,simpleGrantedAuthorities);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        filterChain.doFilter(request,response);



    }
}
